package com.wx.forum.service.impl;

import com.wx.forum.common.AppResult;
import com.wx.forum.common.ResultCode;
import com.wx.forum.dao.UserMapper;
import com.wx.forum.exception.ApplicationException;
import com.wx.forum.model.User;
import com.wx.forum.service.IUserService;
import com.wx.forum.utils.MD5Util;
import com.wx.forum.utils.StringUtil;
import com.wx.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        //判空
        if (user == null || StringUtil.isEmpty(user.getUsername())
                || StringUtil.isEmpty(user.getNickname()) || StringUtil.isEmpty(user.getPassword())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //判断用户是否已经存在
        User exitsUser = userMapper.selectByUsername(user.getUsername());
        if (exitsUser != null) {
            log.warn(ResultCode.FAILED_USER_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        //赋默认值
        // 填充默认值
        if (user.getUsername() == null) {
            user.setGender((byte) 2);
        }
        user.setIaAdmin((byte) 0);
        user.setAvatarUrl(null);
        user.setArticleCount(0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        //写入数据库
        int row = userMapper.insertSelective(user);
        if (row != 1) {
            log.warn(ResultCode.FAILED_CREATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        log.info(ResultCode.SUCCESS.getMessage());
    }

    /**
     * 提供给controller的根据username查询用户信息
     *
     * @param username
     * @return
     */
    @Override
    public User selectByUsername(String username) {
        //判空
        if (StringUtil.isEmpty(username)) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByUsername(username);
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public User login(String username, String password) {
        //1.判空
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        //2.查询用户信息
        User user = selectByUsername(username);
        if (user == null) {//用户不存在
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString() + "username: " + username);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        //3.密码校验
        String salt = user.getSalt();

        String loginPassword = MD5Util.md5Salt(password, salt);
        if (!loginPassword.equals(user.getPassword())) {//密码错误
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString() + "password: " + password);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //密码置空
        if (!StringUtil.isEmpty(user.getPassword()))
            user.setPassword("");

        //4.返回结果
        return user;
    }

    /**
     * 根据id查询用户信息
     *
     * @param id
     * @return
     */
    @Override
    public User selectById(Long id) {
        if (id == null || id == 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询用户信息，并将密码置空
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {//用户不存在
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //密码置空
        if (!StringUtil.isEmpty(user.getPassword()))
            user.setPassword("");
        return user;
    }

    /**
     * 增加用户帖子数量
     *
     * @param id
     */
    @Override
    public void addOneArtcleCountByUserId(Long id) {
        //参数校验
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_USER_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_COUNT));
        }
        //查找用户
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //更新帖子数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);

        int raw = userMapper.updateByPrimaryKeySelective(updateUser);
        if (raw != 1) {
            log.warn(ResultCode.FAILED_USER_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_COUNT));
        }
    }

    @Override
    public void subOneArtcleCountByUserId(Long id) {
        //参数校验
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_USER_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_COUNT));
        }
        //查找用户
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //更新帖子数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        //如果贴子数等于0，就不减
        if (user.getArticleCount() > 0)
            updateUser.setArticleCount(user.getArticleCount() - 1);


        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED_USER_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_COUNT));
        }
    }

    /**
     * 修改用户信息
     *
     * @param user
     */
    @Override
    public void modifyInfo(User user) {
        //1.参数校验
        if (user == null || user.getId() == null || user.getId() <= 0) {
            //打印信息
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.校验用户是否存在
        User existUser = userMapper.selectByPrimaryKey(user.getId());//查询的是数据库里原本的用户信息
        if (existUser == null) {
            //打印信息
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //3.定义一个标志位
        Boolean checkAttr = false;//false表示没有校验通过
        //4.构建更新对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        //4.1判断username是否为空并且不能和原来的username一样
        if (!StringUtil.isEmpty(user.getUsername())
                && !existUser.getUsername().equals(user.getUsername())) {
            //判断是否有重复名
            User checkUser = userMapper.selectByUsername(user.getUsername());
            if (checkUser != null) {
                //打印信息
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                //抛出异常
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            //赋值
            updateUser.setUsername(user.getUsername());
            //更新标志位
            checkAttr = true;
        }

        //4.2校验昵称
        if (!StringUtil.isEmpty(user.getNickname())
                && !existUser.getNickname().equals(user.getNickname())) {
            //赋值
            updateUser.setNickname(user.getNickname());
            //更新标志位
            checkAttr = true;
        }

        //4.3校验性别
        if (user.getGender() != null && user.getGender() != existUser.getGender()) {
            //赋值
            updateUser.setGender(user.getGender());
            //判断合法性
            if (user.getGender() > 2 || user.getGender() < 0) {
                updateUser.setGender((byte) 2);
            }
            //更新标志位
            checkAttr = true;
        }

        //4.4校验邮箱
        if (!StringUtil.isEmpty(user.getEmail())
                && !user.getEmail().equals(existUser.getEmail())) {
            //赋值
            updateUser.setEmail(user.getEmail());
            //更新标志位
            checkAttr = true;
        }

        //4.5校验电话号码
        if (!StringUtil.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existUser.getPhoneNum())) {
            if (user.getPhoneNum().length() != 11) {
                //打印信息
                log.warn(ResultCode.FAILED_PhoneNum_NOT_11.toString());
                //抛出异常
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PhoneNum_NOT_11));
            }
            //赋值
            updateUser.setPhoneNum(user.getPhoneNum());
            //更新标志位
            checkAttr = true;
        }

        //4.6校验个人简洁
        if (!StringUtil.isEmpty(user.getRemark())
                && !user.getRemark().equals(existUser.getRemark())) {
            //赋值
            updateUser.setRemark(user.getRemark());
            //更新标志位
            checkAttr = true;
        }

        //5.判断标志位
        if (checkAttr == false) {
            //打印信息
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    /**
     * 修改密码
     *
     * @param id          用户id
     * @param oldPassword 原密码
     * @param newPassword 新密码
     */
    public void modifyPassword(Long id, String oldPassword, String newPassword) {
        //1.参数校验
        if (id == null || StringUtil.isEmpty(oldPassword) || StringUtil.isEmpty(newPassword)) {
            //打印信息
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.查询用户
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            //打印信息
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //3.判断原密码是否正确
        oldPassword = MD5Util.md5Salt(oldPassword, user.getSalt());
        if (!oldPassword.equals(user.getPassword())) {
            log.warn(ResultCode.FAILED_PASSWORD.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PASSWORD));
        }
        //4.创建新密码
        String newSalt = UUIDUtil.getUUID_32();
        newPassword = MD5Util.md5Salt(newPassword, newSalt);
        //5.构建更新对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setPassword(newPassword);
        updateUser.setSalt(newSalt);
        updateUser.setUpdateTime(new Date());
        //6.调用DAO
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public int updateAvatarUrl(Long userId, String imgUrl) {
        //1.校验数据
        if (userId == null || userId <= 0 || StringUtil.isEmpty(imgUrl)) {
            //打印信息
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //构建更新对象
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setAvatarUrl(imgUrl);
        updateUser.setUpdateTime(new Date());

        return userMapper.updateByPrimaryKeySelective(updateUser);
    }
}
